package com.ruoyi.web.controller.common;

import java.awt.*;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.mysql.cj.util.TimeUtil;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.mytools.AliyunOssUtils;
import com.ruoyi.common.mytools.DateUtils;
import com.ruoyi.common.mytools.R;
import com.ruoyi.common.mytools.jwtUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.Articles;
import com.ruoyi.system.service.IArticlesService;
import org.apache.commons.lang.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.framework.config.ServerConfig;

/**
 * 通用请求处理
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/common")
public class CommonController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private HttpServletRequest httpServletRequest;


    @Resource
    private IArticlesService articlesService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private TokenService tokenService;

    private final String FILE_DELIMETER = ",";




    private int count=1;



    /**
     * 通用下载请求
     * 
     * @param fileName 文件名称
     * @param delete 是否删除
     */
    @GetMapping("/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request)
    {
        try
        {
            if (!FileUtils.checkAllowDownload(fileName))
            {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = RuoYiConfig.getDownloadPath() + fileName;

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete)
            {
                FileUtils.deleteFile(filePath);
            }
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 通用上传请求（多个）
     */
    @PostMapping("/uploads")
    public AjaxResult uploadFiles(List<MultipartFile> files) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            List<String> urls = new ArrayList<String>();
            List<String> fileNames = new ArrayList<String>();
            List<String> newFileNames = new ArrayList<String>();
            List<String> originalFilenames = new ArrayList<String>();
            for (MultipartFile file : files)
            {
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                String url = serverConfig.getUrl() + fileName;
                urls.add(url);
                fileNames.add(fileName);
                newFileNames.add(FileUtils.getName(fileName));
                originalFilenames.add(file.getOriginalFilename());
            }
            AjaxResult ajax = AjaxResult.success();
            ajax.put("urls", StringUtils.join(urls, FILE_DELIMETER));
            ajax.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));
            ajax.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMETER));
            ajax.put("originalFilenames", StringUtils.join(originalFilenames, FILE_DELIMETER));
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 本地资源通用下载
     */
    @GetMapping("/download/resource")
    public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
            throws Exception
    {
        try
        {
            if (!FileUtils.checkAllowDownload(resource))
            {
                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resource));
            }
            // 本地资源路径
            String localPath = RuoYiConfig.getProfile();
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }

       /* @GetMapping("/abc")
    public AjaxResult abc() {
        System.out.println("abc.........");
        return toAjax(0);
    }*/

    //通用图片上传，返回OSS地址
    //@RequestParam("file") MultipartFile multipartFile 单文件上传
    //@RequestPart("files") MultipartFile[] files 多文件上传


    //@PreAuthorize("@ss.hasPermi('system:courses:upload')")
    @Anonymous
    @PostMapping("/OssUploadImage/{dataid}")
    public void OssUploadImage(@RequestPart("file") MultipartFile[] fileArr,@PathVariable("dataid") Integer cid, @RequestHeader(value = "productNo",required = false)String productNo) {
        //System.out.println("调用OSS接口"+count);
        //System.out.println("课程id:"+cid);

        //ImageUpload.imglist.add(file.getName());
        //System.out.println("图片大小:"+ImageUpload.imglist.size());

        // 获取请求携带的令牌
        if(redisTemplate.hasKey("mytoken")) {
            String token = redisTemplate.opsForValue().get("mytoken").toString();
            System.out.println("当前登录token: "+token);

            try {
                System.out.println("上传了"+fileArr.length+"个文件");
                for (int i = 0; i < fileArr.length; i++) {
                    //ImageUpload.imglist.add(fileArr[i].getName());
                    //System.out.println("上传文件"+multipartFile);
                    //System.out.println("登录Token:"+redisTemplate.opsForValue().get("login_tokens:6226e329-9a2f-4542-9239-702a55189e55"));

                    //上传至本地服务器
                    //根据产品编号生成对应的文件夹存放图片
                    //String Productno=products.getProductno();
               /* if(!StringUtils.isEmpty(productNo)){
                    String filename = multipartFile.getOriginalFilename(); //获取文件名
                    String absolutePath="images/productimgs/"+productNo+"/";
                    File savePos = new File("src/main/resources/static/"+absolutePath);
                    if(!savePos.exists()){  // 不存在，则创建该文件夹
                        savePos.mkdir();
                    }
                    String destPath = savePos.getCanonicalPath()+"\\";
                    filename= FileUtils.generateRandomFileName(filename); //生成唯一文件名称 xxx-xxx-xxx.jpg
                    System.out.println("存放目录"+destPath);
                    System.out.println("文件名"+filename);
                    //上传成功返回图片地址
                    uploadImageUrl=FileUtils.uploadFileToServer(multipartFile,destPath,absolutePath,filename);
                }*/

                    //上传至阿里云
                    String OSSimagePathName="images/coursesimg"; //OSS images 目录
                    String uploadFileUrl= AliyunOssUtils.newUploadFile(fileArr[i],OSSimagePathName);
                    System.out.println("uploadFileUrl===>:"+uploadFileUrl);
                    if(!StringUtils.isEmpty(uploadFileUrl)){
                        //sb.append(uploadFileUrl+",");
                        ImageUpload.imglist.add(uploadFileUrl);
                    }

                } //for end

                //更新图片
                /*String coursePhotoList=ArrayUtils.toString(ImageUpload.imglist).replace("[","").replace("]","");
                Courses courses=new Courses();
                courses.setId(Long.valueOf(cid.toString()));
                courses.setCoursephotosList(coursePhotoList);
                coursesService.updateCourses(courses);*/

                //return R.ok("上传成功").put("imglist",ArrayUtils.toString(ImageUpload.imglist).replace("[","").replace("]",""));

            } catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            System.out.println("非法操作");
        }
    }




    @Anonymous
    @PostMapping("/OssUploadImageII/{dataid}")
    public void OssUploadImageII(@RequestPart("file") MultipartFile[] fileArr,@PathVariable("dataid") Long cid) {
        // 获取请求携带的令牌
        if(redisTemplate.hasKey("mytoken")) {
            String token = redisTemplate.opsForValue().get("mytoken").toString();
            System.out.println("当前登录token: "+token);

            try {
                System.out.println("上传了"+fileArr.length+"个文件");
                for (int i = 0; i < fileArr.length; i++) {
                    //上传至阿里云
                    String OSSimagePathName="images/adimgs"; //OSS images 目录
                    String uploadFileUrl= AliyunOssUtils.newUploadFile(fileArr[i],OSSimagePathName);
                    System.out.println("uploadFileUrl===>:"+uploadFileUrl);
                    //更新图片
//                    Activitys activitys=new Activitys();
//                    activitys.s
//                    activitysService.updateActivitys(activitys);etId(Long.valueOf(cid.toString()));
//                    activitys.setAdname(activitysService.selectActivitysById(cid).getAdname());
//                    activitys.setAdimgurl(uploadFileUrl);
                } //for end
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            System.out.println("非法操作");
        }
    }





    /**
     * 课堂风采
     * */
//    @Anonymous
//    @PostMapping("/OssUploadFiles/{dataid}")
//    public void OssUploadFiles(@RequestPart("file") MultipartFile[] fileArr,@PathVariable("dataid") Long cid) {
//        // 获取请求携带的令牌
//        if(redisTemplate.hasKey("mytoken")) {
//            String token = redisTemplate.opsForValue().get("mytoken").toString();
//            System.out.println("当前登录token: "+token);
//            ArrayList<String> imglists=new ArrayList<>();
//            try {
//                System.out.println("上传了"+fileArr.length+"个文件");
//                for (int i = 0; i < fileArr.length; i++) {
//                    //上传至阿里云
//                    String OSSimagePathName="images/attachments"; //OSS images 目录
//                    String uploadFileUrl= AliyunOssUtils.newUploadFile(fileArr[i],OSSimagePathName);
//                    System.out.println("uploadFileUrl===>:"+uploadFileUrl);
//                    //保存图片 返回数组
//                    imglists.add(uploadFileUrl);
//                    TimeUnit.MILLISECONDS.sleep(200);
//                } //for end
//                System.out.println("上传图片数组");
//                imglists.forEach(System.out::println);
//                //更新到数据库
//                //更新图片
//               /* Photos photos=new Photos();
//                photos.setId(Long.valueOf(cid.toString()));
//                photos.setImgphotos(ArrayUtils.toString(imglists));
//                photosService.updatePhotos(photos);*/
//            } catch (Exception e) {
//                System.out.println("上传发生错误:"+e.getMessage());
//                e.printStackTrace();
//            }
//        }else{
//            System.out.println("非法操作");
//        }
//    }


    /**
     * 商家图片上传
     */
    @Anonymous
    @PostMapping("/OssUploadFiles/{dataid}")
    public R OssUploadFiles(@RequestPart("file") MultipartFile[] multipartFile,@PathVariable("dataid") String dataid) {

        // 获取请求携带的令牌
        if(redisTemplate.hasKey("mytoken")) {
            String token = redisTemplate.opsForValue().get("mytoken").toString();
            System.out.println("当前登录token: "+token);

            List<String> filesList=new ArrayList<>();
            String uploadImageUrl="";
            try {
                //上传至本地服务器
                //根据产品编号生成对应的文件夹存放图片
                //String Productno=products.getProductno();
                if(!StringUtils.isEmpty(dataid)){
                    System.out.println("上传了"+multipartFile.length+"个文件");
                    for (int i = 0; i < multipartFile.length; i++) {
                        String filename = multipartFile[i].getOriginalFilename(); //获取文件名
//                        String absolutePath="images/attachments/"+dataid+"/";
//                        File savePos = new File("ruoyi-admin/src/main/resources/static/"+absolutePath);
                        String absolutePath="C:\\attachments\\"+dataid+"\\";
                        File savePos = new File(absolutePath);
                        if(!savePos.exists()){  // 不存在，则创建该文件夹
                            savePos.mkdir();
                        }
                        String destPath = savePos.getCanonicalPath()+"\\";
                        String realName=filename;
                        filename= com.ruoyi.common.mytools.FileUtils.generateRandomFileName(filename); //生成唯一文件名称 xxx-xxx-xxx.jpg
                        System.out.println("存放目录"+destPath);
                        System.out.println("文件名"+filename);
                        //上传成功返回图片地址
                        uploadImageUrl=dataid+"#"+realName+"#"+com.ruoyi.common.mytools.FileUtils.uploadFileToServer(multipartFile[i],destPath,"attachments/"+dataid+"/",filename)+"#"+ DateUtils.YMD();
                        filesList.add(uploadImageUrl);
                    }
                }//*/

                //读取id数据
                Articles articlesData=articlesService.selectArticlesById(Long.valueOf(dataid));
                List<String> mergedList = new ArrayList<>();

                try{
                    //先追加之前的数组数组
                    if(!StringUtils.isEmpty(articlesData.getAttachments())) {
                        String arr = articlesData.getAttachments().replace("[", "").replace("]", "");
                        List<String> oldlist = Arrays.asList(arr.split(","));
                        //合并list1
                        mergedList.addAll(oldlist); //旧数据
                    }
                }catch (Exception ex){

                }

                //合并list2
                mergedList.addAll(filesList); //新数据

                //更新链接数据
                articlesData.setAttachments(ArrayUtils.toString(mergedList));
                articlesService.updateArticles(articlesData);

                //return R.ok("上传成功").put("imglist",ArrayUtils.toString(ImageUpload.imglist).replace("[","").replace("]",""));

                if(!StringUtils.isEmpty(uploadImageUrl)){
                    return R.ok().put("uploadImageUrl",uploadImageUrl);
                }


            } catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            System.out.println("非法操作");
        }

        return R.error(400,"图片上传失败");
    }


} // class end
